import React, {Component} from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Checkbox,
  Radio,
  Modal,
  Icon,
  message,
  Card,
  AutoComplete,
  DatePicker,
  Table,
  List,
  Upload,
  Avatar,
} from 'antd';
import myaxios, {get, put, post} from 'common/fetch';
import {
  SEARCH_USER_INFO_URL,
  CATEGORY_URL,
  UPLOAD_URL,
  POLL_URL,
} from 'constant/url';
import moment from 'moment';

const RadioGroup = Radio.Group,
  FormItem = Form.Item,
  TextArea = Input.TextArea;

const DATE_FORMAT = 'YYYY-MM-DD HH:mm';

class CreateDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList: this.props.editData.upload || [],
    };
  }
  handleChange = ({fileList}) => {
    if (
      fileList.length > 0 &&
      fileList[0].status == 'done' &&
      fileList[0].response.code == 0
    ) {
      let fileObj = {};
      fileObj.url = fileList[0].response.data.url;
      fileObj.name = fileList[0].name;
      fileObj.uid = 1;
    }
    console.log(fileList);
    console.log(fileList.length);
    this.setState({fileList});
  };
  _beforeUpload = (file, fileList) => {
    let fileSize = 1024 * 1024;
    if (file.size / fileSize >= 1) {
      const size =
        1024 > fileSize
          ? fileSize + 'B'
          : 1024 * 1024 > fileSize
            ? fileSize / 1024 + 'KB'
            : fileSize / 1024 / 1024 + 'M';
      message.error('图片请保证在' + size + '以内');
      return false;
    }
    return true;
  };
  normFile = e => {
    if (Array.isArray(e)) {
      console.log('Upload event:', e);
      return e;
    }
    console.log('Upload event:', e && e.fileList);
    return e && e.fileList;
  };
  render() {
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 14},
      },
    };
    const {getFieldDecorator} = this.props.form;
    const {isEdit, editData} = this.props,
      {fileList} = this.state;
    return (
      <Form>
        <FormItem {...formItemLayout} label="标题">
          {getFieldDecorator('title', {
            rules: [{required: true, message: '请输入标题'}],
            initialValue: isEdit ? editData.title : '',
          })(<Input />)}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="上传图片"
          extra=".jpg、.jpeg、.png">
          {getFieldDecorator('upload', {
            initialValue: fileList,
            valuePropName: 'fileList',
            getValueFromEvent: this.normFile,
          })(
            <Upload
              name="files"
              accept="image/*"
              action={UPLOAD_URL}
              fileList={fileList}
              beforeUpload={this._beforeUpload}
              onChange={this.handleChange}
              listType="picture">
              <Button disabled={fileList.length > 0}>
                <Icon type="upload" /> 上传图片
              </Button>
            </Upload>,
          )}
        </FormItem>
      </Form>
    );
  }
}
const CreateDialogForm = Form.create()(CreateDialog);

class Poll extends Component {
  constructor(props) {
    super(props);
    this.state = {
      categoryId: null,
      choiceList: [],
      isEdit: false,
      showModal: false,
      pollTime: moment().format(DATE_FORMAT),
      editData: {},
    };
  }
  timePickerOnChange = value => {
    const pollTime = moment(value).format(DATE_FORMAT);
    this.setState({
      pollTime,
    });
  };
  // 确认按钮
  handleOk() {
    const {choiceList, pollTime} = this.state,
      {postId} = this.props,
      title = this.refs.pollTitle.input.value;
    if (choiceList.length < 1 || !title || !pollTime) {
      return message.error('请填写完整信息！');
    }
    choiceList.map(item => {
      delete item.upload;
    });
    post(`${POLL_URL}/add`, {
      question: title,
      endAt: pollTime,
      postId,
      choice: choiceList,
    }).then(res => {
      this.props.reloadPostDetail();
      this.props.hidePanel();
    });
  }
  // 添加投票选项
  handleCreateNew = () => {
    this.setState({
      isEdit: false,
      showModal: true,
    });
  };
  handleCancel = () => {
    this.setState({
      isEdit: false,
      showModal: false,
      editData: {},
    });
  };
  handleEdit = (record, index) => {
    this.setState({
      isEdit: true,
      showModal: true,
      editData: {...record, index},
    });
  };
  handleDelete = index => {
    const choiceList = [...this.state.choiceList];
    choiceList.splice(index, 1);
    this.setState({
      choiceList,
    });
  };
  handleModalOk = () => {
    const {isEdit, editData} = this.state;
    const choiceList = [...this.state.choiceList];
    this.refs.CreateDialogForm.validateFields((err, values) => {
      if (!err) {
        console.log(values);
        const valuesRel = {
          ...values,
          img:
            values.upload &&
            values.upload[0] &&
            values.upload[0].response &&
            values.upload[0].response.data &&
            values.upload[0].response.data.url,
        };
        if (isEdit) {
          choiceList[editData.index] = valuesRel;
        } else {
          choiceList.push(valuesRel);
        }
      }
      this.setState({
        choiceList,
        showModal: false,
        editData: {},
      });
    });
  };
  render() {
    const {choiceList, isEdit, editData, showModal, pollTime} = this.state;

    return (
      <div>
        <h5 className="panel-custom-title">设置</h5>
        <Card title="投票信息" style={{margin: 20}} bordered={false}>
          <div className="msg-assign-wrapper">
            <div>
              <div className="mb10">请填写投票标题：</div>
              <div className="mt10 mb10">
                <Input ref="pollTitle" placeholder="请填写投票标题" />
              </div>
              <div className="mb10">请选择结束时间：</div>
              <div className="mt10 mb10">
                <DatePicker
                  showTime
                  format={DATE_FORMAT}
                  placeholder="请选择结束时间"
                  onOk={this.timePickerOnChange}
                />
              </div>
              <div className="mb10">设置选项：</div>
              <div className="mt10">
                <List
                  size="large"
                  dataSource={choiceList}
                  header={
                    <Button
                      type="dashed"
                      onClick={this.handleCreateNew}
                      icon="plus">
                      添加
                    </Button>
                  }
                  renderItem={(item, index) => (
                    <List.Item
                      key={index}
                      actions={[
                        <a onClick={() => this.handleEdit(item, index)}>
                          编辑
                        </a>,
                        <a onClick={() => this.handleDelete(index)}>删除</a>,
                      ]}
                      extra={
                        item.img && (
                          <img width={272} alt="logo" src={item.img} />
                        )
                      }>
                      {index + 1}.{item.title}
                    </List.Item>
                  )}
                />
              </div>
            </div>
          </div>
        </Card>
        <Button
          type="primary"
          className="mt30 ml20"
          onClick={this.handleOk.bind(this)}>
          确定
        </Button>
        {showModal && (
          <Modal
            visible={showModal}
            wrapClassName="vertical-center-modal default-popup"
            onCancel={this.handleCancel}
            onOk={this.handleModalOk}
            title={`${isEdit ? '编辑' : '新增'}投票选项`}
            okText="确定"
            cancelText="取消">
            <CreateDialogForm
              uploadFileChange={this.uploadFileChange}
              ref="CreateDialogForm"
              isEdit={isEdit}
              editData={editData}
            />
          </Modal>
        )}
      </div>
    );
  }
}

export default Poll;
